//
//  AdvertViewController.m
//  FullShareTop
//
//  Created by lqq on 2017/7/10.
//  Copyright © 2017年 FSB. All rights reserved.
//

#import "AdvertViewController.h"
#import "I_APPManager.h"
#import <SDWebImageDownloader.h>
@interface AdvertViewController () <CAAnimationDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *adImageView;

@property (weak, nonatomic) IBOutlet UIView *animationBackView;
@property (weak, nonatomic) IBOutlet UIView *innerView;
@property (nonatomic, strong) CAShapeLayer *arcLayer;

@property (nonatomic, strong) NSMutableArray *advertList;
@property (nonatomic, strong) M_Advert *currentAdvert;
@end

@implementation AdvertViewController
#pragma mark - Class Methed
+ (instancetype)controller
{
    AdvertViewController *adVC = [[AdvertViewController alloc] initWithNibName:@"AdvertViewController" bundle:nil];
    return adVC;
}


#pragma mark - Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self requestAdvert];
    
    //图片加载手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedImage)];
    [self.adImageView addGestureRecognizer:tap];
    
    //innerView
    _innerView.layer.cornerRadius = 15;
    _innerView.layer.masksToBounds = YES;
    
    _animationBackView.hidden = YES;
    

}

-(void)dealloc
{
    NSLog(@"%s",__func__);
}


#pragma mark - NET
- (void)requestAdvert
{
    __weak __typeof (self)weakSelf = self;
    [I_APPManager requestAdvertOnSuccess:^(NSMutableArray *advertList) {
        [NSObject cancelPreviousPerformRequestsWithTarget:weakSelf selector:@selector(overleapLoadAdvert) object:nil];
        weakSelf.advertList = [NSMutableArray array];
        for (M_Advert *advert in advertList) {
            if (!([[NSDate date] timeIntervalSince1970] > [advert.expireTime longLongValue] / 1000)) {
                //没有过期
                [weakSelf.advertList addObject:advert];
            }
        }
        if (weakSelf.advertList.count == 0) {//错误地址
            [weakSelf overleapLoadAdvert];
        } else {
            //加载图片
            [weakSelf loadImage];
        }
        
    } failure:^(NSError *error) {
        [NSObject cancelPreviousPerformRequestsWithTarget:weakSelf selector:@selector(overleapLoadAdvert) object:nil];
        [weakSelf overleapLoadAdvert];
    }];
    
    //1秒之后如果数据未加载完成忽略加载
    [self performSelector:@selector(overleapLoadAdvert) withObject:nil afterDelay:1];
    
    
}

#pragma mark - Pravite Methed

/**
 忽略加载广告
 */
- (void)overleapLoadAdvert
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(changeImage:) object:nil];
    [_arcLayer removeAllAnimations];
    if (self.overleapBlock) {
        self.overleapBlock();
    }
}


/**
 加载图片
 */
- (void)loadImage
{
   
    //
    for (int i = 0 ; i < _advertList.count; i++) {
        M_Advert *advert = _advertList[i];
        [self loadImageWithAdvert:advert];
    }
    //3秒之后如果图片未加载完成,忽略加载
    [self performSelector:@selector(overleapLoadAdvert) withObject:nil afterDelay:3];
}

- (void)loadImageWithAdvert:(M_Advert *)advert
{
    static int i = 0;
    __weak __typeof (self)weakSelf = self;
    
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:advert.advertPic] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        i++;
        advert.image = image;
        if (i == weakSelf.advertList.count) {//图片全部加载完成
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.adImageView.userInteractionEnabled = YES;
                //一定时间内图片加载成功，停止忽略
                [NSObject cancelPreviousPerformRequestsWithTarget:weakSelf selector:@selector(overleapLoadAdvert) object:nil];
                
                //开始动画
                weakSelf.animationBackView.hidden = NO;
                [weakSelf countDownAnimation];
            });
         
        }

    }];
//    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:advert.advertPic] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//        
//    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
//        i++;
//        advert.image = image;
//        if (i == weakSelf.advertList.count) {//图片全部加载完成
//            weakSelf.adImageView.userInteractionEnabled = YES;
//            //一定时间内图片加载成功，停止忽略
//            [NSObject cancelPreviousPerformRequestsWithTarget:weakSelf selector:@selector(overleapLoadAdvert) object:nil];
//            
//            //开始动画
//            weakSelf.animationBackView.hidden = NO;
//            [weakSelf countDownAnimation];
//        }
//    }];
}


/**
 点击图片
 */
- (void)clickedImage
{
    if (_currentAdvert.jumpType) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(changeImage:) object:nil];
        [_arcLayer removeAllAnimations];
        if (_clickedAdvertBlock) {
            _clickedAdvertBlock(_currentAdvert);
        }
    }
}

/**
 点击跳过按钮
 */
- (IBAction)jumpOver:(id)sender {
    [self overleapLoadAdvert];
}


/**
 倒计时动画
 */
- (void)countDownAnimation
{
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path addArcWithCenter:CGPointMake(17, 17) radius:16 startAngle:-M_PI/ 2 endAngle:(-2*M_PI-M_PI/ 2)  clockwise:NO];
    CAShapeLayer *arcLayer = [CAShapeLayer layer];
    arcLayer.path = path.CGPath;
    //arcLayer.strokeColor可设置画笔颜色
    arcLayer.lineWidth = 2;
    arcLayer.frame = CGRectMake(0, 0, 32, 32);
    arcLayer.fillColor = [UIColor clearColor].CGColor;
    arcLayer.strokeColor = [UIColor colorWithHexString:@"#3AA7FF"].CGColor;
    [_animationBackView.layer addSublayer:arcLayer];
    _arcLayer = arcLayer;

    CABasicAnimation *bas = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    
    CGFloat totalTime = 0;
    for (M_Advert *advert in _advertList) {
        [self performSelector:@selector(changeImage:) withObject:advert afterDelay:totalTime / 1000];
        totalTime += advert.delayTime;

    }
    bas.duration = totalTime / 1000.0;
   
    bas.delegate = self;
    bas.fromValue = [NSNumber numberWithInteger:1];
    bas.toValue = [NSNumber numberWithInteger:0];
    
    //动画执行完之后保持原状
    bas.removedOnCompletion = NO;
    bas.fillMode = kCAFillModeForwards;
    
    [arcLayer addAnimation:bas forKey:@"key"];

}

- (void)changeImage:(id)sender
{
    M_Advert *advert = sender;
    _currentAdvert = advert;
    if (_currentAdvert.image) {
        self.adImageView.image = _currentAdvert.image;
    }
}


#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
//    [_arcLayer removeFromSuperlayer];
//    _animationBackView.hidden = YES;
    
    if (flag) {
        [self overleapLoadAdvert];
    }
}
@end





